const {BrowserWindow, ipcMain, dialog } = require('electron');
const path = require('path')
const configTool = require('../tool/config')
const UpdClient = require('../net/udp_client')
const UdpServer = require('../net/udp')
const TcpServer = require('../net/tcp')
const TcpClient = require('../net/tcp_client')

configTool.init()

let selectFiles = async () => {
  const { canceled, filePaths } = await dialog.showOpenDialog({
    title: "选择传送文件",
    properties: ['multiSelections'],
    filters: [
    ]
  })

  return  canceled ? [] : filePaths
}
function getBroadCastInfo() {
  return UdpServer.getInstant().netInfo
}

function setBroadCastInfo(evn, data) {
  console.log(data)
  UdpServer.getInstant().setBroadCastInfo(data)
}

function sendFiles(evn, data) {
  console.log(data)

  data.list.map(v => {
    let obj = new TcpClient()
    obj.send(data.ip ,v)
  })
}


function createIndex () {
  const win = new BrowserWindow({
    width: 1000,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, '../preload/index.js')
    }
  })

  let udpObj = UpdClient.getInstant()
  udpObj.onUpdate = (link)=>{
    win.webContents.send('update-link', link)
  }
  udpObj.init()

  let updServerObj = UdpServer.getInstant()
  updServerObj.init()

  let tcpObj = TcpServer.getInstant()
  tcpObj.onUpdate = (data)=>{
    win.webContents.send('update-fileRecive', data)
  }
  tcpObj.init()
  
  ipcMain.handle('selectFiles', selectFiles)
  ipcMain.handle('getBroadCastInfo', getBroadCastInfo)
  ipcMain.handle('setBroadCastInfo', setBroadCastInfo)
  ipcMain.handle('sendFiles', sendFiles)

  win.webContents.openDevTools()
  win.loadURL('http://localhost:3000/')
  //win.loadFile('dist/index.html')

}

module.exports = {
  createIndex
}
